package com.photoeditor.demo.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.common.base.utils.SystemUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ProtocolUtil {

    /**
     * 获取包名
     */
    public static String getPackageName(Context context) {
        String packageName = null;
        if (context != null) {
            packageName = context.getPackageName();
        }
        return packageName;
    }

    /**
     * 日志打印时间
     */
    public static String getLogPrintTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date());
    }

    /**
     * os 用户手机操作系统的版本信息，如android-2.3.7
     */
    public static String getOS() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 用户手机型号，如GT-I9000
     */
    public static String getModel() {
        return Build.MODEL;
    }

    public static String getBrand() {
        return Build.BRAND;
    }

    /**
     * 获取国家
     */
//    public static String getCountry(Context context) {
//        String ret = null;
//
//        try {
//            TelephonyManager telManager = (TelephonyManager) context
//                    .getSystemService(Context.TELEPHONY_SERVICE);
//            if (telManager != null) {
//                ret = telManager.getSimCountryIso().toUpperCase();
//            }
//        } catch (Throwable e) {
//            //             e.printStackTrace();
//        }
//        if (ret == null || ret.equals("")) {
//            ret = Locale.getDefault().getCountry();
//        }
//        return ret;
//    }



    public static String getLanguage(Context context) {
        String ret = null;

        try {
            TelephonyManager telManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (telManager != null) {
                ret = telManager.getSimCountryIso().toUpperCase();
            }
        } catch (Throwable e) {
            //             e.printStackTrace();
        }
        if (ret == null || ret.equals("")) {
            ret = Locale.getDefault().getLanguage();
        }
        return ret;
    }

    /**
     * 读取渠道
     */
    public static String getMyChannel(Context context) {
        final String start_flag = "META-INF/channel_";
        String ret = "";
        if (context != null) {
            ApplicationInfo appinfo = context.getApplicationInfo();
            String sourceDir = appinfo.sourceDir;
            ZipFile zipfile = null;
            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    String entryName = entry.getName();
                    if (entryName.contains(start_flag)) {
                        ret = entryName.replace(start_flag, "");
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (zipfile != null) {
                    try {
                        zipfile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ret;
    }

    /**
     * 是否是新用户
     * 客户端判断的新用户标识：0-否, 1-是;
     */
    public static boolean getNewUser(Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        if (sp != null) {
            if (sp.getBoolean("is_first_run", true)) {
                sp.edit().putBoolean("is_first_run", false).apply();
                return true;
            } else {
                return false;
            }
        }
        return false;
    }


    private static final String DEFAULT_RANDOM_DEVICE_ID = "0000000000000000";

    private static final String SHARED_PREFERENCES_DEVICE_ID = "device_id";                                                                        // 存储IMEI号的sharedPreference名称

    private static final String SHARED_PREFERENCES_RANDOM_ID = "random_id";

    /**
     * 申请权限获取手机的IMEI号
     */
    public static String getVirtualIMEI(Context context) {
        //如果已保存IMEI或者存在旧的虚拟IMEI号则直接使用。
        String imei = getDeviceIdFromSharedPreference(context);
        // 获取手机的IMEI，并保存下来
        if (context != null) {
            if (null == imei || imei.equals(DEFAULT_RANDOM_DEVICE_ID)) {
                try {
                    imei = SystemUtils.getIMEI(context);
                    saveDeviceIdToSharedPreference(context, Long.valueOf(imei));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return imei;
    }



    /**
     * 获取随机生成的IMEI的方法
     */
    private static String getDeviceIdFromSharedPreference(Context context) {
        if (context == null) {
            return null;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(
                SHARED_PREFERENCES_DEVICE_ID, Context.MODE_PRIVATE);
        return sharedPreferences.getString(SHARED_PREFERENCES_RANDOM_ID, DEFAULT_RANDOM_DEVICE_ID);
    }

    /**
     * 保存随机生成的IMEI的方法
     */
    private static void saveDeviceIdToSharedPreference(Context context, long deviceId) {
        if (context == null) {
            return;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(
                SHARED_PREFERENCES_DEVICE_ID, Context.MODE_PRIVATE);
        String device = String.valueOf(deviceId);
        sharedPreferences.edit().putString(SHARED_PREFERENCES_RANDOM_ID, device).apply();
    }

    public static String getAndroidId() {
        String androidId;
        Context context = ComponentContext.getContext();
        try {
            androidId = android.provider.Settings.Secure.getString(context.getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);
            if (TextUtils.isEmpty(androidId)) {
                SharedPreferences sharedPreferences = context.getSharedPreferences(
                        SHARED_PREFERENCES_DEVICE_ID, Context.MODE_PRIVATE);
                String defaultId;
                Random random = new Random();
                defaultId = String.valueOf(random.nextLong());
                androidId = sharedPreferences.getString(SHARED_PREFERENCES_RANDOM_ID, defaultId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            androidId = DEFAULT_RANDOM_DEVICE_ID;
        }
        return androidId;
    }

}

